<?php

namespace App\Http\Controllers;

use App\Http\Requests\LoginRequest;
use App\Models\Admin;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;

class UserController  extends Controller
{
    public function login(LoginRequest $loginRequest){
        $data = [
            'username' =>  $loginRequest->post('username',''),
            'pwd' =>  $loginRequest->post('pwd',''),
            'captcha' => $loginRequest->post('captcha',''),
            'ck' => $loginRequest->post('ck','')
        ];
        if (!captcha_api_check($data['captcha'] , $data['ck'])){
            cp_return(__('message.captcha_error'));
        }
        $token = md5(md5(time()));
        $adminModel = (new User());
        $userInfo = $adminModel->where('username',$data['username'])->where('status',1)->first();
        if(!$userInfo){
            cp_return(__('message.login_error'));
        }

        if (!Hash::check($data['pwd'], $userInfo->pwd)) {
            cp_return(__('message.login_error'));
        }

        // 检查键是否已存在
        if (Redis::exists($token)) {
            // 如果键已存在，则更新过期时间
            Redis::pexpire($token, 24 * 60 * 60 * 1000);
            return c_return(0,[
                'token' => Redis::get($token)
            ]);
        } else {
            // 如果键不存在，则设置新的键值并设置过期时间
            Redis::psetex($token, 24 * 60 * 60 * 1000, $token);
        }
        return c_return(0,[
            'token' => $token
        ]);
    }

    public function checkToken(){
        http_response_code(401); // 未授权
    }
}
